//
//  HomeViewController.swift
//  WB
//
//  Created by leador on 17/3/17.
//  Copyright © 2017年 袁满. All rights reserved.
//

import UIKit
import SDWebImage
import MJRefresh

class HomeViewController: BaseTableViewController {

    lazy var titleBtn:TitleButton = TitleButton()
    lazy var popoverAni:PopoverAnimator = PopoverAnimator{[weak self] (isPresented)->() in
    
        self?.titleBtn.isSelected = isPresented
        
    }
    
    lazy var viewModels:[StatusViewModel] = [StatusViewModel]()
    
    lazy var tipLabel:UILabel = UILabel()
    
    var temp = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        visitorView.addRotationAnim()
        if !isLogin {
            return
        }
        
        //依据约束来动态计算高度
//        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.estimatedRowHeight = 200 //设置估算高度
        
        setupNavigationBar()
        
        //布局header
        setupHeaderView()
        
        //布局footer
        setupFooterView()
        
        //刷新时的顶部提示框
        setupTipLabel()

        setupNotification()
    }

}

//MARK: ---UI界面---
extension HomeViewController {
    
    func setupNavigationBar() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName:"navigationbar_friendattention")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName:"navigationbar_pop")
        
        titleBtn.setTitle("yuanman", for: .normal)
        titleBtn.addTarget(self, action: #selector(HomeViewController.titleBtnClick(titleBtn:)), for: .touchUpInside)
        navigationItem.titleView = titleBtn
        
    }
    
    func setupHeaderView() {
        
        let header = MJRefreshNormalHeader(refreshingTarget: self, refreshingAction:#selector(loadNewStatuses))
        header?.setTitle("下拉刷新", for: .idle)
        header?.setTitle("释放更新", for: .pulling)
        header?.setTitle("加载中...", for: .refreshing)
        tableView.mj_header = header
        
        tableView.mj_header.beginRefreshing()
        
    }
    
    func setupFooterView() {
        
        tableView.mj_footer = MJRefreshAutoFooter(refreshingTarget:self, refreshingAction: #selector(loadMoreStatuses))
        
    }
    
    func setupTipLabel() {
        
        navigationController?.navigationBar.insertSubview(tipLabel, at: 0)
        tipLabel.frame = CGRect(x:0,y:19,width:kScreenWidth,height:25)
        tipLabel.backgroundColor = UIColor.orange
        tipLabel.textColor = UIColor.white
        tipLabel.font = UIFont.systemFont(ofSize: 12)
        tipLabel.textAlignment = .center
        tipLabel.isHidden = true

    }
    
    func setupNotification() {
        
         NotificationCenter.default.addObserver(self, selector: #selector(showPhotoBrowerClick), name:NSNotification.Name(rawValue: showPhotoBrowerNotification), object: nil)
        
    }
    
}

//MARK: ---事件监听---
extension HomeViewController {
    
    func titleBtnClick(titleBtn:TitleButton) {
        
        //弹出视图
        let popover = PopViewController()
        popover.modalPresentationStyle = .custom
        popoverAni.presentedFrame = CGRect(x:60,y:55,width:200,height:250)
        popoverAni.presentedTransitionDuration = 0.5
        popover.transitioningDelegate = popoverAni
        present(popover, animated: true, completion: nil)
        
    }
    
    func showPhotoBrowerClick(note:Notification) {
        
        let indexPath = note.userInfo?[showPhotoBrowerIndexPathKey] as! NSIndexPath
        
        let picUrls = note.userInfo?[showPhotoBrowerUrlsKey] as! [URL]
        
        let photoBrower = PhotoBrowerViewController(indexPath: indexPath, picUrls: picUrls)
        
        present(photoBrower, animated: true, completion: nil)
    }
    
}

//MARK: ---请求数据---
extension HomeViewController {
    
    //MARK: ---下拉刷新数据---
    func loadNewStatuses() {
        loadStatues(isNewData: true)
    }
    
    //MARK: ---上拉加载数据---
    func loadMoreStatuses() {
        loadStatues(isNewData: false)
    }
    
    
    func loadStatues(isNewData:Bool) {
        
        var since_id = 0
        var max_id = 0
        
        if isNewData {
            since_id = viewModels.first?.status?.mid ?? 0
        }else {
            max_id = viewModels.last?.status?.mid ?? 0
            
            max_id = max_id==0 ? 0 : (max_id-1)
            
        }
        
        NetworkTools.shareInstance.loadStatuses(since_id: since_id, max_id: max_id) { (result, error) in
            
            if error != nil {
                return
            }
            
            guard let resultArray = result else {
                return
            }
            
            var tempModels = [StatusViewModel]()
            for statuesDict in resultArray {
                let status = Status(dict:statuesDict)
                let viewModel = StatusViewModel(status:status)
                tempModels.append(viewModel)
            }
            
            if isNewData {
                self.viewModels = tempModels + self.viewModels
            }else {
                self.viewModels = self.viewModels + tempModels
            }
            
            self.cacheImages(statusViewModels: tempModels)
            
        }
    
    }
    
    //MARK: ---缓存图片的方法---
    func cacheImages(statusViewModels:[StatusViewModel]) {
        
        let group = DispatchGroup()
        
        for viewModel in statusViewModels {
            
            for picURL in viewModel.picURLs {
                
                group.enter()
                SDWebImageManager.shared().loadImage(with: picURL, options: [], progress: nil, completed: { (_, _, _, _, _, _) in
                    
                    print("下载了一张图片")
                    group.leave()
                    
                })
                
            }
            
        }
        
        group.notify(queue: DispatchQueue.main, execute: {
            print("刷新表格")
            self.tableView.reloadData()
            self.tableView.mj_header.endRefreshing()
            self.tableView.mj_footer.endRefreshing()
            
            self.showTiplabel(count: statusViewModels.count)
        })
        
    }
    
    //MARK: ---提示框---
    func showTiplabel(count:Int) {
        
        if temp > 0 {
            return
        }
        
        temp = 1
        
        tipLabel.isHidden = false
        tipLabel.text = count==0 ? "没有新数据" : "\(count)条新微博"
        
        UIView.animate(withDuration: 1, animations: { 
            self.tipLabel.frame.origin.y = 44
        }) { (_) in
            UIView.animate(withDuration: 1, delay: 1.5, options: [], animations: { 
                self.tipLabel.frame.origin.y = 19
            }, completion: { (_) in
                self.tipLabel.isHidden = true
                self.temp = 0
            })
        }
        
    }
    
}

extension HomeViewController {
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return viewModels.count
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "HomeCellID") as! HomeTableViewCell
        
        cell.viewModel = viewModels[indexPath.row]
        
        return cell
        
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        
        let viewModel = viewModels[indexPath.row]
        return viewModel.cellHeight
        
    }

}
